Note that the “<>” brackets indicate the average kinetic energy of each atom in the system.
For our simple system of four moving atoms, it is easy to calculate the average kinetic energy at every time step, so we can calculate the temperature.
To achieve a desired temperature is a little more challenging.
In any system, all of the atoms do not move at the same velocity. The atoms have a range of different velocities, and the velocity of any single atom constantly changes due to interactions with other particles. However, the fraction of a large number of atoms (or molecules) within a particular velocity range is nearly constant if the system is at or near equilibrium, thus leading to temperature. To simulate these fluctuations, we define the initial velocities of the system randomly according to a Maxwell–Boltzmann distribution (which is a normal distribution for velocities) about a desired mean. The Maxwell distribution of velocities specifies this fraction, for any velocity range, as a function of the temperature of the system.
After each timestep, we can then scale the actual velocities of each atom (which are random) according to the desired mean velocity (from the Maxwell-Boltzmann distribution), to attempt to attain the desired temperature. That is why in the simulation, there is a slight difference between required velocity and average velocity. The required velocity is the velocity calculated from the temperature-velocity relation, while the average velocity is calculated based on the actual, random velocities of the atoms at each timestep.
Thermal Expansion
The remaining question: Why does a material expand when there is an increase in temperature?
Short answer: An increase in energy results in an increase in equilibrium spacing of the atomic bonds.
Long answer: Thermal expansion is due to the anharmonicity of the atom interactions [2]. As the temperature rises the amplitude of the crystal lattice vibrations increases, but the equilibrium distance shifts as the atoms spend more time at distances greater than the original spacing due as the repulsion at short distances is greater than the corresponding attraction at farther distances.
Conceptually, when the temperature is increased, you can think of the potential energy of the system “filling” the energy well of the bonding potential: